package com.hibase.core.mq.redis.util;

import com.alibaba.fastjson.JSON;
import com.hibase.common.constant.RedisKeyConstant;
import com.hibase.core.mq.component.HibaseDelayQueueUtil;
import com.hibase.core.redis.util.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.math.BigDecimal;
import java.util.concurrent.TimeUnit;

/**
 * @author chenfeng
 * @version 1.0
 * @date 2021/7/23 13:38
 * @des https://gitee.com/cheershi
 */
@Component
@Slf4j
public class HibaseDelayRedisQueueUtil implements HibaseDelayQueueUtil {

    @Autowired
    private RedisUtil redisUtil;

    /**
     * 通用添加redis-queue
     * @param topic
     * @param msg
     */
    @Override
    public void offer(String topic, Object msg, Long time, TimeUnit timeUnit){
        BigDecimal score = new BigDecimal(System.currentTimeMillis());
        switch (timeUnit){
            case NANOSECONDS:
                score = score.add(new BigDecimal(time).divide(new BigDecimal(1000*1000)));
                break;
            case MICROSECONDS:
                score = score.add(new BigDecimal(time).divide(new BigDecimal(1000)));
                break;
            case MILLISECONDS:
                score = score.add(new BigDecimal(time));
                break;
            case SECONDS:
                score = score.add(new BigDecimal(time).multiply(new BigDecimal(1000)));
                break;
            case MINUTES:
                score = score.add(new BigDecimal(time).multiply(new BigDecimal(1000*60)));
                break;
            case HOURS:
                score = score.add(new BigDecimal(time).multiply(new BigDecimal(1000*60*60)));
                break;
            case DAYS:
                score = score.add(new BigDecimal(time).multiply(new BigDecimal(1000*60*60*24)));
                break;
            default:
                break;
        }
        redisUtil.zAdd(RedisKeyConstant.DELAY_QUEUE_PREFIX_KEY+topic,JSON.toJSONString(msg),score.doubleValue());
        log.info("【Redis-Delay-Queue】 插入 redis Delay QUEUE {} | 数据 : {}",topic,msg);
    }
}
